<!DOCTYPE html>
<html>
	<head>
		<title>TinyShock Pong Demo</title>
		<script src="tinyshock.js"></script>
<script>
// Singleton classes
var ball = new function() {
	var self = this;
	self.mov_x = 2;
	self.mov_y = 1;

	self.onLaunch = function() {
		self.rect = new Rect(TinyShock.screen.getWidth() / 2, TinyShock.screen.getHeight() / 2, 10, 10);
	};
	self.update = function() {
		var estimated = self.rect.move(self.mov_x, 0); // Estimated position after X movement
		if (leftPaddle.rect.collideRect(estimated) || rightPaddle.rect.collideRect(estimated)) {
			self.mov_x *= -1;
		}
		estimated = self.rect.move(0, self.mov_y); // Estimated position after Y movement
		if (estimated.y < 0) {
			self.mov_y *= -1;
		} else if (estimated.bottom() > TinyShock.screen.getHeight()) {
			self.mov_y *= -1;
		}

		self.rect.moveIP(self.mov_x, self.mov_y);
	};
	self.draw = function(screen) {
		screen.fill("green", self.rect);
	};
};
var leftPaddle = new function() {
	var self = this;
	self.speed = 0;
	self.rect = new Rect(10, 10, 15, 70);

	self.update = function() {
		self.rect.y += self.speed;
		return;
	};

	self.processEvent = function(event) {
		if (event.type == "keydown") {
			if (event.key == KEY.DOWN) {
				self.speed = 2;
			} else if (event.key == KEY.UP) {
				self.speed = -2;
			}
		} else if (event.type == "keyup") {
			if (event.key == KEY.DOWN && self.speed == 2) {
				self.speed = 0;
			} else if (event.key == KEY.UP && self.speed == -2) {
				self.speed = 0;
			}
		}
	};

	self.draw = function(screen) {
		screen.fill("red", self.rect);
	};
};
var rightPaddle = new function() {
	var self = this;

	self.onLaunch = function() {
		self.rect = new Rect(TinyShock.screen.getWidth() - 25, 10, 15, 70);
	};
	self.update = function() {
		if (self.rect.centerY() < ball.rect.centerY()) {
			if (ball.rect.centerY() - self.rect.centerY() < 5) {
				self.rect.y = ball.rect.centerY() - self.rect.h / 2;
			} else {
				self.rect.y += 3;
			}
		} else if (ball.rect.centerY() < self.rect.centerY()) {
			if (ball.rect.centerY() - self.rect.centerY() < 4) {
				self.rect.y = ball.rect.centerY() - self.rect.h / 2;
			} else {
				self.rect.y -= 3;
			}
		}
	};
	self.draw = function(screen) {
		screen.fill("blue", self.rect);
	};
};
function go() {
	initTS("screen", 640, 480);

	TinyShock.clearEveryFrame = true;

	TinyShock.register(leftPaddle);
	TinyShock.register(ball);
	TinyShock.register(rightPaddle);

	TinyShock.setBPS(60);

	TinyShock.launch();
}
</script>
	</head>

	<body bgcolor="black" onload="go()">
		<div align="center">
			<canvas id="screen">You need HTML5 to view this page.</canvas>
			<p align="center" style="color: white;">Use the arrow keys to move your paddle.</p>
		</div>
	</body>
</html>


